package com.qingge.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingge.springboot.common.Result;
import com.qingge.springboot.entity.PaperTest;
import com.qingge.springboot.entity.Test;
import com.qingge.springboot.service.IPaperService;
import com.qingge.springboot.service.IPaperTestService;
import com.qingge.springboot.service.ITestService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/paperTest")
public class PaperTestController {

    @Resource
    private IPaperTestService paperService;

    @Resource
    private ITestService testService;

    @GetMapping("/getOption/{paperId}")
    public Result getOptionsByTestId(@PathVariable String paperId){
        //先查询试卷应用的试题
        LambdaQueryWrapper<PaperTest> paperTestLambdaQueryWrapper = new LambdaQueryWrapper<>();
        paperTestLambdaQueryWrapper.eq(PaperTest::getPaperId,paperId);
        List<PaperTest> paperTests = paperService.getBaseMapper().selectList(paperTestLambdaQueryWrapper);
        List<Integer> collect = paperTests.stream().map(PaperTest::getTestId).collect(Collectors.toList());
        //再查询试题具体信息
        List<Test> tests = testService.getBaseMapper().selectBatchIds(collect);
        return Result.success(tests);
    }

    @PostMapping("/saveInfo/{PaperId}")
    @Transactional
    public Result saveInfo(@RequestBody List<Test> list, @PathVariable Integer PaperId){
            //先清除所有存在的考题
        try {
            LambdaQueryWrapper<PaperTest> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PaperTest::getPaperId,PaperId);
            paperService.remove(queryWrapper);
            //然后将数据再进行插入
            List<PaperTest> paperTests = new ArrayList<>();
            List<PaperTest> collect = list.stream().map(item -> {
                return new PaperTest(PaperId, item.getId());
            }).collect(Collectors.toList());
            paperService.saveBatch(collect);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
        return Result.success();
    }


    @GetMapping("/getTest/{paperId}")
    public Result getTest(@PathVariable String paperId){
        LambdaQueryWrapper<PaperTest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaperTest::getPaperId,paperId);
        List<PaperTest> paperTests = paperService.getBaseMapper().selectList(queryWrapper);
        Stream<Integer> testIds = paperTests.stream().map(PaperTest::getTestId);
        return Result.success(paperTests);
    }
}
